#include "relation.h"

#include <QStyleOptionGraphicsItem>
#include <QtMath>
#include <QDebug>
#include <QPen>
#include <QPainter>
#include "diagramscene.h"
#include <QtMath>
Relation::Relation(QObject* parent):QObject(parent)
{
    setFlag(QGraphicsItem::ItemIsSelectable, true);
    setPen(QPen(myColor, 5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    setFlag(QGraphicsItem::ItemIsMovable, false);
    setAcceptHoverEvents(true);

}

Relation::~Relation()
{
    qDebug()<<__func__;
}
QRectF Relation::boundingRect() const
{
    qreal extra = (width + 20) / 2.0;

    return QRectF(line().p1(), QSizeF(line().p2().x() - line().p1().x(),
                                      line().p2().y() - line().p1().y()))
        .normalized()
        .adjusted(-extra, -extra, extra, extra);
}



void Relation::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget)
{
    painter->setRenderHint(QPainter::Antialiasing);

    QPen myPen = pen();
    myPen.setStyle(Qt::SolidLine);
    myPen.setColor(myColor);
    myPen.setWidth(width);

    painter->setBrush(myColor);
    painter->setPen(myPen);

    painter->drawLine(line());
    painter->drawPolygon(myPolygon);
}

QPainterPath Relation::shape() const
{
    QPainterPath path = QGraphicsLineItem::shape();
    path.addPolygon(myPolygon);
    return path;
}


Relation::DIRECTION Relation::direction() const
{
    return m_direction;
}

void Relation::addArrow(int _direction)
{
    m_direction = (DIRECTION)_direction;
    QPointF p2 = line().p2();
    if(line().isNull() || line().p2().isNull())
    {
        return ;
    }
    m_direction = (DIRECTION)_direction;
    myPolygon.clear();
    myPolygon.append(p2);
    switch (_direction) {
    case UP:
        myPolygon.append(QPointF(p2.rx()-arrowWidth,p2.ry()+arrowWidth));
        myPolygon.append(QPointF(p2.rx()+arrowWidth,p2.ry()+arrowWidth));
        break;
    case DOWN:
        myPolygon.append(QPointF(p2.rx()-arrowWidth,p2.ry()-arrowWidth));
        myPolygon.append(QPointF(p2.rx()+arrowWidth,p2.ry()-arrowWidth));
        break;
    case LEFT:
        myPolygon.append(QPointF(p2.rx()+arrowWidth,p2.ry()-arrowWidth));
        myPolygon.append(QPointF(p2.rx()+arrowWidth,p2.ry()+arrowWidth));
        break;
    case RIGHT:
        myPolygon.append(QPointF(p2.rx()-arrowWidth,p2.ry()-arrowWidth));
        myPolygon.append(QPointF(p2.rx()-arrowWidth,p2.ry()+arrowWidth));
        break;
    default:
        qDebug()<<__func__<<" is error";
        break;
    }
    update();
}


